package org.longsheng.learnspringboot.controller;

import lombok.Data;
import org.apache.commons.lang3.SerializationUtils;
import org.longsheng.learnspringboot.entity.User;
import org.longsheng.learnspringboot.model.UserModel;
import org.longsheng.learnspringboot.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author DingQiao
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/getUser")
    public UserModel getUser() {
        User user = userRepository.findByUserName("bb");
        System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");

        // 浅拷贝，非引用类型的字段没问题
        UserModel result = new UserModel();
        BeanUtils.copyProperties(user, result);
        result.setUserName("DingQiao");
        System.out.printf("user:%s, userModel:%s%n", user.getUserName(), result.getUserName());

        DTOTest dto1 = new DTOTest();
        dto1.setName("dto1");
        dto1.setUsers(new ArrayList<>());
        dto1.getUsers().add(user);

        // 浅拷贝，引用类型拷贝不了
        DTOTest dto2 = new DTOTest();
        BeanUtils.copyProperties(dto1, dto2);
        dto2.getUsers().get(0).setUserName("DingQiao2");

        // 深拷贝
        DTOTest dto3 = SerializationUtils.clone(dto1);
        dto3.getUsers().get(0).setUserName("DingQiao3");

        // 结果：dto1:DingQiao2, dto2:DingQiao2, dto3:DingQiao3
        System.out.printf("dto1:%s, dto2:%s, dto3:%s%n", dto1.getUsers().get(0).getUserName(), dto2.getUsers().get(0).getUserName(), dto3.getUsers().get(0).getUserName());

        return result;
    }

    @RequestMapping("/getUsers")
    @Cacheable(value = "user-list")
    public List<User> getUsers() {
        List<User> users = userRepository.findAll();
        System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
        return users;
    }

    /**
     * session + redis测试
     * @param session
     * @return
     */
    @RequestMapping("/uid")
    String uid(HttpSession session) {
        UUID uid = (UUID) session.getAttribute("uid");
        if (uid == null) {
            uid = UUID.randomUUID();
        }

        session.setAttribute("uid", uid);
        return session.getId();
    }
}

@Data
class DTOTest implements Serializable {
    String name;

    List<User> users;
}

@Data
class DTOTest2 implements Serializable {
    String name;

    List<User> users;
}